package com.zyl.points.service;  
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Random;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.zyl.points.Main;
import com.zyl.points.bean.Question;
import com.zyl.points.bean.Task;
import com.zyl.points.util.DBHelper;

/**
 * 题库
 * @param  
 * @return
 */
public class QuestionService {  
      
        private DBHelper helper;  
        private Task task;
        private TaskService taskService;
        
        
        public QuestionService(Context context) {  
            helper = new DBHelper(context);//初始化数据库  
            task=Task.getInstance(context);
            taskService=new TaskService(context);
        }  
      
        /**  
         * 插入一个Question  
         * @param p 要插入的Question  
         */  
        public void insert(Question q) {  
            SQLiteDatabase db = helper.getWritableDatabase();  //获取到数据库  
            db.execSQL("INSERT INTO Question(title,answer,appearTimes) VALUES(?,?,?)", new Object[] { q.getTitle(), q.getAnswer(), q.getAppearTimes() });  
            db.close();  
        }  
      
        /**  
         * 根据ID删除  
         * @param id 要删除的Question的ID  
         */  
        public void delete(Integer id) {  
            SQLiteDatabase db = helper.getWritableDatabase();  
            db.execSQL("DELETE FROM Question WHERE id=?", new Object[] { id });  
            db.close();  
        }  
      
        public void reduceAppearTimes(Integer qid) {  
            SQLiteDatabase db = helper.getWritableDatabase();  
             db.execSQL("UPDATE Question SET  appearTimes=appearTimes-1 WHERE id=?", new Object[] {  qid });  
            db.close();  
        }  
        public void addAppearTimes(Integer qid) {  
        	SQLiteDatabase db = helper.getWritableDatabase();  
        	db.execSQL("UPDATE Question SET  appearTimes=appearTimes+1 WHERE id=?", new Object[] {  qid });  
        	db.close();  
        }  
        /**  
         * 
         * 这里主要是分组 逻辑 和判断 是否 是完结 最后一位的逻辑
         * 根据ID查找  
         * @param Integer id,Integer page,Integer size
         * @return 对应的对象, 如果未找到返回null  
         */  
        public Question next() {  
        	// 是否  最后一位的 如果是 从组的开头再来 最后 还是空的话 就finsh
        	//如果是最后一组的 话逻辑是呢?是不是应该在task里判断
        	
	        int size=task.getSize();
	        int page=task.getPage();
        	int start =(page - 1) * size  ;
        	if( task.getQid()>=size*page) {
    			int count = findPageCount(page,size );
    			if(count==0){
    				task.setPage(page + 1);
    				taskService.updatePage(page + 1);
    				task.setFinsh(true); 
    				}else{
    				task.setQid(start);
    				}
    		}
            
    		Question q = nextQuestion(task.getQid());  
    		
    		if(q==null) 
    			q = nextQuestion(start);	
    		
            return q;  
        }  
        
        public Question nextQuestion(Integer id ) {  
            SQLiteDatabase db = helper.getReadableDatabase();  
            Cursor cursor = db.rawQuery("SELECT title,answer,appearTimes,id FROM Question WHERE id>? and  appearTimes>0  order by id asc limit 1", new String[] { id.toString() });  
            Question q = null;  
            if (cursor.moveToNext()) {  
                String title = cursor.getString(0);  
                String answer = cursor.getString(1);  
                Integer appearTimes = cursor.getInt(2);  
                Integer qid = cursor.getInt(3);  
                q = new Question(qid, title, answer, appearTimes);  
            }  
            cursor.close();  
            db.close();  
            return q;  
        }  
        
        
        public Question randomQuestion( ) {  
            SQLiteDatabase db = helper.getReadableDatabase();  
            Cursor cursor = db.rawQuery("SELECT title,answer,appearTimes,id FROM Question WHERE   appearTimes>0  order by id asc limit 1", null);  
            Question q = null;  
            if (cursor.moveToNext()) {  
                String title = cursor.getString(0);  
                String answer = cursor.getString(1);  
                Integer appearTimes = cursor.getInt(2);  
                Integer qid = cursor.getInt(3);  
                q = new Question(qid, title, answer, appearTimes);  
            }  
            cursor.close();  
            db.close();  
            return q;  
        }  
        
        /**  
         * 查询所有Question对象  
         * @return Question对象集合, 如未找到, 返回一个size()为0的List  
         */  
        public List<Question> findAll() {  
            SQLiteDatabase db = helper.getReadableDatabase();  
            Cursor cursor = db.rawQuery("SELECT id,title,answer,appearTimes FROM Question", null);  
            List<Question> Questions = new ArrayList<Question>();  
            while (cursor.moveToNext()) {  
                Integer id = cursor.getInt(0);  
                String title = cursor.getString(1);  
                String answer = cursor.getString(2);  
                Integer appearTimes = cursor.getInt(3);  
                Questions.add(new Question(id, title, answer, appearTimes));  
            }  
            cursor.close();  
            db.close();  
            return Questions;  
        }  
      

        public HashSet<Integer> random4num(int index ,int total) {

    		HashSet<Integer> hs = new HashSet<Integer>();
    		Random rand = new Random();
    		int randInt = 1;
    		hs.add(index);
    		while (hs.size() < 4) {
    			randInt = rand.nextInt(total)+1;
    			hs.add(randInt);
    		}
    		return hs;
    	}
        public List<Question> getOptionList(Question current) {  
		Integer total = task.getTotalCount();
		if (total == null || total == 0)
			return null;
		List<Question> questions = new ArrayList<Question>(4);
		
		int currentid=current.getId();
        HashSet<Integer> hs = random4num(currentid ,total);
    	SQLiteDatabase db = helper.getReadableDatabase();
     
    	Cursor cursor =null;
		for (Integer index : hs) {
			if(index==currentid)questions.add(current);else{
				cursor = db.rawQuery(
								"SELECT id,title,answer,appearTimes FROM Question where id=?",
								new String[] { index + "" });
				
				while (cursor.moveToNext()) {
					Integer id = cursor.getInt(0);
					String title = cursor.getString(1);
					String answer = cursor.getString(2);
					Integer appearTimes = cursor.getInt(3);
					questions.add(new Question(id, title, answer, appearTimes));
				}
			     cursor.close();
			}
		}
	
		task.setRightIndex(questions.indexOf(current));
		task.setCurrent(current);
        task.setQid(current.getId());
        taskService.update(task);
	   
			db.close();
            return questions;  
        }  
 
        public List<Question> nextList( ){
        	Question current =next( );
        	if(current==null)return null;
        	return getOptionList(current);
        }

        /**  
         * 查询某一页数据  
         * @param page 页码  
         * @param size 每页记录数  
         * @return  
         */  
        public List<Question> findPage(int page, int size) {  
            SQLiteDatabase db = helper.getReadableDatabase();  
            Cursor cursor = db.rawQuery("SELECT id,title,answer,appearTimes FROM Question where appearTimes>0 LIMIT ?,?" //  
                    , new String[] { String.valueOf((page - 1) * size), String.valueOf(size) });  
            List<Question> Questions = new ArrayList<Question>();  
            while (cursor.moveToNext()) {  
                Integer id = cursor.getInt(0);  
                String title = cursor.getString(1);  
                String answer = cursor.getString(2);  
                Integer appearTimes = cursor.getInt(3);  
                Questions.add(new Question(id, title, answer, appearTimes));  
            }  
            cursor.close();  
            db.close();  
            return Questions;  
        }  
        /**  
         * 查询某一页数据  
         * @param page 页码  
         * @param size 每页记录数  
         * @return  
         */  
        public int findPageCount(int page, int size) {  
        	SQLiteDatabase db = helper.getReadableDatabase();  
        	int count =0;
        	Cursor cursor = db.rawQuery("SELECT ID FROM Question where appearTimes>0 and id>? and id<?" //  
        			, new String[] { String.valueOf((page - 1)*size), String.valueOf(page*size) });  
        	count = cursor.getCount();  
        	cursor.close();  
        	db.close();  
        	return count;  
        }  

}  

